<?php

/**
 * 用户分组信息
 *
 * Class GroupInfoAction
 *
 * @auth 刘鹏 2017/6/25
 * @modify LLyeap <LL_strive@163.com> 2017-11-25
 */
class GroupInfoAction extends Action
{

    /**
     * 添加与修改分组
     *
     * @param string $groupId   群组的id
     * @param        $groupName 群组的名称
     */
    public function saveGroup($groupId = '', $groupName)
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user["customerId"];
        $fullName = Session::$user["fullName"];
        $id = Session::$user["id"];
        Session::switchCustomer(0);
        $userGroup=D("group_info");
        Session::switchCustomer($customerId);
        $date['groupName']=$groupName;
        $date['cid']=$customerId;
        $date['userId']=$id;
        $where['groupName']=array('eq',$groupName);
        $where['deleted']=array('eq',0);
        $where['cid'] = $customerId;
        if($groupId){
            $where['groupId']=array('neq',$groupId);
        }

        $arr=$userGroup->where($where)->select();
        if(!empty($arr)){
            $return['code']=2;
            $return['msg']='分组名称已存在';
            Output::instance()->objArray($return);
            return;
        }

        if($groupId) {
            $data["id"]=$groupId;
            $result=$userGroup->save($date);

            $content_sql = $userGroup->getLastSql();    //获取最后一条sql语句
            R('Log/add',array('accessControl','130','访问控制',op_update,$content_sql,$fullName.'修改'.$groupName.'用户分组'));

        } else {
            $date['deleted']=0;
            $time=date("Y-m-d H:i:s");
            $date['createTime']=$time;
            $result=$userGroup->add($date);

            $content_sql = $userGroup->getLastSql();    //获取最后一条sql语句
            R('Log/add',array('accessControl','130','访问控制',op_add,$content_sql,$fullName.'添加'.$groupName.'用户分组'));
        }

        if ($result) {
            $return['code']=0;
            $return['msg']='添加成功';
            Output::instance()->objArray($return);
        } else {
            $return['code']=1;
            $return['msg']='添加失败';
            Output::instance()->objArray($return);
        }
    }

//    删除分组（假删除）
    public function deleteGroup($groupid)
    {

        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user["customerId"];
        $fullName = Session::$user["fullName"];


        Session::switchCustomer(0);
        $userGroup = M("group_info");
        $group_user = M("group_user");
        Session::switchCustomer($customerId);
        $result = $userGroup->where(['id' => $groupid])->setField("deleted", 1);//假删除
        $group_user->where(['infoId' => $groupid])->delete();

        $groupName = $userGroup->where("id=$groupid")->getField("groupName", true);
        $content_sql = $userGroup->getLastSql();    //获取最后一条sql语句
        R('Log/add',array('accessControl','130','访问控制',op_delete,$content_sql,$fullName.'删除'.$groupName[0].'用户分组'));
        if ($result) {
            Output::instance()->resultCode(code_success);
        } else {
            Output::instance()->resultCode(code_sql_error);
        }
    }

//    获取所有组信息以及组长
    public function groupList($start=0,$limit=10, $keyword = '')

    {

        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user["customerId"];
        Session::switchCustomer(0);
//      实例化开发平台数据模型
        $Group=D('group_info');
//      实例化开发平台数据模型
        $userGroup=D('group_user as a');
//        判断是获取组信息和单个组的用户信息
        $where["cid"]=array('eq',$customerId);
        $where["deleted"]=array('eq',0);
        if (!empty($keyword)) {
            $where['groupName'] = ['LIKE', '%' . $keyword . '%'];
        }

        $arr=$Group->order('id desc')->where($where)->field('id,groupName,createTime')->limit($start,$limit)->select();
        Session::switchCustomer($customerId);
//        查询一共有多少个分组
        $count=$Group->where($where)->count();
        if ($arr) {
            foreach($arr as $k=>$v) {
                $wheres['infoId']=$v['id'];
                $wheres['leader']=1;
                $arr[$k]['leader']=$userGroup->order(array('a.id'=>'desc'))->where($wheres)->join('wx_customer_user as b on a.userId=b.id')->field('userId,loginName,fullName')->select();
            }
            Output::instance()->objArray($arr,$count);
        } else {
            Output::instance()->resultCode(code_success);
        }
    }

    /**
     * 获取所有成员的信息 - 在组内的默认选择
     * - 调优提示: 这地方将查询所有用户和查询该分组用户写在一起, 查询该分组用户之前, 先查出了所有, 再去除. 这里可以做一步优化
     *
     * @param        $groupId   分组id
     * @param string $keyword   关键字搜索
     * @param int    $isAll     是否查询所有: 1-查询所有用户/0-查询该分组用户
     */
    public function groupUser($groupId, $keyword = '', $isAll = 1)
    {
        /** 1. 判断登录 */
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        /** 2. 实例化模型 */
        $id = Session::$user["id"];
        $customerId = Session::$user["customerId"];
        Session::switchCustomer(0);
        $group = D('group_user');
        $customer_user = D('customer_user');
        
        /** 3. 查询条件 */
        $where = [
            'id'    => ['NEQ', $id],
            'customerId'    => $customerId,
            'agent'     => 'insideUser',
            'status'    => 'open',
        ];
        if (!empty($keyword)) $where['fullName|phone'] = ['LIKE', '%' . $keyword . '%'];

        /** 4. 查询所有用户 */
        $arr = $customer_user
            ->where($where)
            ->field('id, loginName, fullName, phone')
            ->select();
        $arr = !empty($arr) ? $arr : [];

        // 查询出已在组内的成员
        $data = $group->where(['infoId' => $groupId])->getField('userId, leader');

        /** 5. 处理数据 */
        foreach ($arr as $key => $value) {
            if (isset($data[$value['id']])) {   // 把已在组内的成员默认选择
                $arr[$key]['default'] = 1;
                $arr[$key]['leader'] = $data[$value['id']];
            } else {    // 否则, 该成员未在组里
                if ($isAll == 0) {  // 只查询该分组用户
                    unset($arr[$key]);
                    continue;
                }

                $arr[$key]['default'] = 0;
                $arr[$key]['leader'] = 0;
            }
        }

        /** 6. 返回 */
        $Out = [
            'code'  => 0,
            'total' => count($arr),
            'results'   => $arr
        ];
        Output::instance()->object($Out);
    }

    /**
     * 修改组内的成员信息
     *    $groupId:组id
     *    $userId：用户id  （以逗号分隔）
     *    $leader：设置为组长的用户id  （以逗号分隔）
     */
    public function saveGroupUser($groupId,$userId,$leaderId){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user["customerId"];

        $fullName = Session::$user["fullName"];


        Session::switchCustomer(0);
        $groupUser=D('group_user');
        $userGroup=D('group_info');
        Session::switchCustomer($customerId);
//        把用户id分割成数组
        $userIds=explode(',',$userId);
//        把为组长的用户id分割成数组
        $leaders=explode(',',$leaderId);
//        删除组内原有的用户
        $result = $groupUser->where("infoId=$groupId")->delete();
        if(empty($userId)){
            Output::instance()->resultCode(code_success);
            return;
        }

//        向组内添加用户
        foreach($userIds as $value) {
            if(in_array($value,$leaders)) {
                $data['infoId']=$groupId;
                $data['userId']=$value;
                $data['leader']=1;
                $re=$groupUser->add($data);
                continue;
            }
            $data['infoId']=$groupId;
            $data['userId']=$value;
            $data['leader']=0;
            $re=$groupUser->add($data);
            $content_sql = $groupUser->getLastSql();
            //获取最后一条sql语句
//            R('Log/add', array('store', '87','门店',  op_add,$content_sql));   //调方法写日志
            $groupName = $userGroup->where("id=$groupId")->getField("groupName", true);
            R('Log/add',array('accessControl','130','访问控制',op_update,$content_sql,$fullName.'修改'.$groupName[0].'用户分组'));


        }
//        判断是否添加成功
        if ($re) {
            Output::instance()->resultCode(code_success);
            return;
        } else {
            Output::instance()->resultCode(code_sql_error);
            return;
        }
    }
}


?>